#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/tcp.h>

void error_handing(char *message)
{
    fputs(message,stderr);
    fputc('\n',stderr);
    exit(1);
}
int main(int argc, char const *argv[])
{
    //步骤1：创建套接字
    int server_sock;
    server_sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
    if (server_sock == -1)
    {
        error_handing("socket() error");
    }
    
    int send_buf,receive_buf;
    int send_buf_size = sizeof(send_buf);
    int receive_buf_size = sizeof(receive_buf);

    //查询默认输出缓冲区大小
    if(getsockopt(server_sock,SOL_SOCKET,SO_SNDBUF,(void *)&send_buf,(socklen_t *)&send_buf_size) == -1)
    {
        error_handing("getsockopt() error");
    }

    //查询默认输入缓冲区大小
    if(getsockopt(server_sock,SOL_SOCKET,SO_RCVBUF,(void *)&receive_buf,(socklen_t *)&receive_buf_size) == -1)
    {
        error_handing("getsockopt() error");
    }

    //打印结果
    printf("默认输出缓冲区大小：%d\n",send_buf);
    printf("默认输入缓冲区大小：%d\n",receive_buf);

    send_buf = 4 * 1024;
    receive_buf = 4 * 1024;

   //设置输出缓冲区大小
    if(setsockopt(server_sock,SOL_SOCKET,SO_SNDBUF,(void *)&send_buf,(socklen_t)send_buf_size) == -1)
    {
        error_handing("setsockopt() error");
    }

    //设置输入缓冲区大小
    if(setsockopt(server_sock,SOL_SOCKET,SO_RCVBUF,(void *)&receive_buf,(socklen_t)receive_buf_size) == -1)
    {
        error_handing("setsockopt() error");
    }
    
    //查询输出缓冲区大小
    if(getsockopt(server_sock,SOL_SOCKET,SO_SNDBUF,(void *)&send_buf,(socklen_t *)&send_buf_size) == -1)
    {
        error_handing("getsockopt() error");
    }

    //查询输入缓冲区大小
    if(getsockopt(server_sock,SOL_SOCKET,SO_RCVBUF,(void *)&receive_buf,(socklen_t *)&receive_buf_size) == -1)
    {
        error_handing("getsockopt() error");
    }

    //打印结果
    printf("设置之后的输出缓冲区大小：%d\n",send_buf);
    printf("设置之后的输入缓冲区大小：%d\n",receive_buf);

    close(server_sock);
    return 0;
}
